using System.Text;
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;

namespace BlazeApps.Library.Polls
{
    [Serializable()]
    public class PollQuestionDetail : Csla.BusinessBase<PollQuestionDetail>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _pollId = Guid.NewGuid();
        private string _pollQuestion = string.Empty;
        private SmartDate _ExpirationDate = new SmartDate(false);
        private Guid _UserID = Guid.Empty;
        private SmartDate _CreateDate = new SmartDate(DateTime.Today);
        private bool _closed = false;
        private decimal _answerCount = 0;

        [System.ComponentModel.DataObjectField(true, false)]
        public Guid PollId
        {
            get
            {
                CanReadProperty("PollId", true);
                return _pollId;
            }
            set
            {
                CanWriteProperty("PollId", true);
                if (!_pollId.Equals(value))
                {
                    _pollId = value;
                    PropertyHasChanged("PollId");
                }
            }
        }

        public string PollQuestion
        {
            get
            {
                CanReadProperty("PollQuestion", true);
                return _pollQuestion;
            }
            set
            {
                CanWriteProperty("PollQuestion", true);
                if (value == null)
                    value = string.Empty;
                if (!_pollQuestion.Equals(value))
                {
                    _pollQuestion = value;
                    PropertyHasChanged("PollQuestion");
                }
            }
        }

        public DateTime ExpirationDate
        {
            get
            {
                CanReadProperty("ExpirationDate", true);
                return _ExpirationDate.Date;
            }
        }

        public string ExpirationDateString
        {
            get
            {
                CanReadProperty("ExpirationDateString", true);
                return _ExpirationDate.Text;
            }
            set
            {
                CanWriteProperty("ExpirationDateString", true);
                if (value == null)
                    value = string.Empty;
                if (!_ExpirationDate.Equals(value))
                {
                    _ExpirationDate.Text = value;
                    PropertyHasChanged("ExpirationDateString");
                }
            }
        }

        public Guid UserID
        {
            get
            {
                CanReadProperty("UserID", true);
                return _UserID;
            }
            set
            {
                CanWriteProperty("UserID", true);
                if (!_UserID.Equals(value))
                {
                    _UserID = value;
                    PropertyHasChanged("UserID");
                }
            }
        }

        public DateTime CreateDate
        {
            get
            {
                CanReadProperty("CreateDate", true);
                return _CreateDate.Date;
            }
        }

        public string CreateDateString
        {
            get
            {
                CanReadProperty("CreateDateString", true);
                return _CreateDate.Text;
            }
            set
            {
                CanWriteProperty("CreateDateString", true);
                if (value == null)
                    value = string.Empty;
                if (!_CreateDate.Equals(value))
                {
                    _CreateDate.Text = value;
                    PropertyHasChanged("CreateDateString");
                }
            }
        }

        public bool Closed
        {
            get
            {
                CanReadProperty("Closed", true);
                return _closed;
            }
            set
            {
                CanWriteProperty("Closed", true);
                if (!_closed.Equals(value))
                {
                    _closed = value;
                    PropertyHasChanged("Closed");
                }
            }
        }

        public decimal AnswerCount
        {
            get
            {
                CanReadProperty("AnswerCount", true);
                return _answerCount;
            }
            set
            {
                CanWriteProperty("AnswerCount", true);
                if (!_answerCount.Equals(value))
                {
                    _answerCount = value;
                    PropertyHasChanged("AnswerCount");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _pollId;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // PollQuestion
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "PollQuestion");
            //
            // CreatedOn
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "CreateDateString");
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in PollQuestionDetail
            //AuthorizationRules.AllowRead("PollId", "PollQuestionDetailReadGroup");
            //AuthorizationRules.AllowRead("SiteId", "PollQuestionDetailReadGroup");
            //AuthorizationRules.AllowRead("PollQuestion", "PollQuestionDetailReadGroup");
            //AuthorizationRules.AllowRead("CloseType", "PollQuestionDetailReadGroup");
            //AuthorizationRules.AllowRead("CloseDate", "PollQuestionDetailReadGroup");
            //AuthorizationRules.AllowRead("CloseDateString", "PollQuestionDetailReadGroup");
            //AuthorizationRules.AllowRead("CreatedBy", "PollQuestionDetailReadGroup");
            //AuthorizationRules.AllowRead("CreatedOn", "PollQuestionDetailReadGroup");
            //AuthorizationRules.AllowRead("CreatedOnString", "PollQuestionDetailReadGroup");
            //AuthorizationRules.AllowRead("Closed", "PollQuestionDetailReadGroup");
            //AuthorizationRules.AllowRead("AnswerCount", "PollQuestionDetailReadGroup");

            //AuthorizationRules.AllowWrite("SiteId", "PollQuestionDetailWriteGroup");
            //AuthorizationRules.AllowWrite("PollQuestion", "PollQuestionDetailWriteGroup");
            //AuthorizationRules.AllowWrite("CloseType", "PollQuestionDetailWriteGroup");
            //AuthorizationRules.AllowWrite("CloseDateString", "PollQuestionDetailWriteGroup");
            //AuthorizationRules.AllowWrite("CreatedBy", "PollQuestionDetailWriteGroup");
            //AuthorizationRules.AllowWrite("CreatedOnString", "PollQuestionDetailWriteGroup");
            //AuthorizationRules.AllowWrite("Closed", "PollQuestionDetailWriteGroup");
            //AuthorizationRules.AllowWrite("AnswerCount", "PollQuestionDetailWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in PollQuestionDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PollQuestionDetailViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in PollQuestionDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PollQuestionDetailAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in PollQuestionDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PollQuestionDetailEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in PollQuestionDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PollQuestionDetailDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private PollQuestionDetail()
        { /* require use of factory method */
        }

        public static PollQuestionDetail NewPollQuestionDetail()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a PollQuestionDetail");
            return DataPortal.Create<PollQuestionDetail>();
        }

        public static PollQuestionDetail GetPollQuestionDetail(Guid pollId)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a PollQuestionDetail");
            return DataPortal.Fetch<PollQuestionDetail>(new Criteria(pollId));
        }

        public static void DeletePollQuestionDetail(Guid pollId)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a PollQuestionDetail");
            DataPortal.Delete(new Criteria(pollId));
        }

        public override PollQuestionDetail Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a PollQuestionDetail");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a PollQuestionDetail");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a PollQuestionDetail");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid PollId;

            public Criteria(Guid pollId)
            {
                this.PollId = pollId;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@PollId", criteria.PollId);

            using(SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetPollQuestionByPollID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            _pollQuestion = dr.GetString("PollQuestion");
            _ExpirationDate = dr.GetSmartDate("ExpirationDate", _ExpirationDate.EmptyIsMin);
            _UserID = dr.GetGuid("UserID");
            _CreateDate = dr.GetSmartDate("CreateDate", _CreateDate.EmptyIsMin);
            _closed = dr.GetBoolean("Closed");
            _answerCount = dr.GetDecimal("AnswerCount");
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertPollQuestion.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@pollid", _pollId);
            DAL.AddParameter("@PollQuestion", _pollQuestion);
            DAL.AddParameter("@ExpirationDate", _ExpirationDate.DBValue);
            DAL.AddParameter("@UserID", _UserID);
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdatePollQuestion.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@PollId", _pollId);
            DAL.AddParameter("@PollQuestion", _pollQuestion);
            DAL.AddParameter("@ExpirationDate", _ExpirationDate.DBValue);
        }

        private void UpdateChildren(SqlConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_pollId));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery(Procs.DeletePollQuestion.ToString().Trim(), CommandType.Text, ConnectionState.Open);
            Procs.PurgeItemsByItemID(criteria.PollId);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@pollid", criteria.PollId);
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
